package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.ProjectProgressOriginal.ProjectProgressSuper;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class RegistProjectProgressFragment extends Fragment implements OnClickListener {
  public static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.RegistProjectProgressFragment.EXTRA_CONTENT";
  public static final String EXTRA_PROJECT_ID =
      "com.isunland.managesystem.ui.RegistProjectProgressFragment.EXTRA_PROJECT_ID";
  public static final String EXTRA_PROJECT_NAME =
      "com.isunland.managesystem.ui.RegistProjectProgressFragment.EXTRA_PROJECT_NAME";
  public static final String EXTRA_PM_ID =
      "com.isunland.managesystem.ui.RegistProjectProgressFragment.EXTRA_PM_ID";
  private static final int START_DATE = 0;
  private static final int END_DATE = 1;

  private TextView mTvprojectName;
  private TextView mTvprojectState;
  private TextView mTvprojectplanStartTime;
  private TextView mTvprojectPlanEndTime;
  private TextView mTvprojectKeepTime;
  private TextView mTvprojectDelayTime;
  private TextView mTvprojectStartTime;
  private ImageView mIbprojectstart;
  private TextView mTvprojectEndTime;
  private ImageView mIbprojectend;
  private EditText mEtdelayCause;
  private EditText mEtprojectRemark;

  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private ProjectProgressSuper superContent;
  private String projectName = "";
  private String startDate = "";
  private String endDate = "";
  private int requestCode;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar()
        .setTitle(R.string.projecProgressRegist);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    superContent = (ProjectProgressSuper) getArguments().getSerializable(EXTRA_CONTENT);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    projectName = (String) getArguments().getSerializable(EXTRA_PROJECT_NAME);
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;
      case R.id.menu_item_confirm:

        volleyRegist();

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_progress_regist, container, false);
    initData(v);
    return v;
  }

  private void initData(View v) {
    mTvprojectName = (TextView) v.findViewById(R.id.tv_projectName);
    mTvprojectState = (TextView) v.findViewById(R.id.et_projectState);
    mTvprojectplanStartTime = (TextView) v.findViewById(R.id.tv_projectplanStartTime);
    mTvprojectPlanEndTime = (TextView) v.findViewById(R.id.tv_projectPlanEndTime);
    mTvprojectKeepTime = (TextView) v.findViewById(R.id.tv_projectKeepTime);
    mTvprojectDelayTime = (TextView) v.findViewById(R.id.tv_projectDelayTime);
    mTvprojectStartTime = (TextView) v.findViewById(R.id.tv_projectStartTime);
    mIbprojectstart = (ImageView) v.findViewById(R.id.ib_project_start);
    mTvprojectEndTime = (TextView) v.findViewById(R.id.tv_projectEndTime);
    mIbprojectend = (ImageView) v.findViewById(R.id.ib_project_end);
    mEtdelayCause = (EditText) v.findViewById(R.id.et_delayCause);
    mEtprojectRemark = (EditText) v.findViewById(R.id.et_projectRemark);
    mTvprojectName.setText(projectName);
    mTvprojectState.setText(superContent.getStageName());
    mTvprojectplanStartTime.setText(superContent.getPlanSTime());
    mTvprojectPlanEndTime.setText(superContent.getPlanETime());
    mTvprojectKeepTime.setText(superContent.getActAllDaynum());
    mTvprojectDelayTime.setText(superContent.getPostDays());
    mTvprojectStartTime.setText(startDate);
    mIbprojectstart.setOnClickListener(this);
    mIbprojectend.setOnClickListener(this);
  }

  @Override public void onClick(View v) {
    DialogFragment dialog = null;

    switch (v.getId()) {
      case R.id.ib_project_start:
        dialog = new BaseYMDTimeDialogFragment();
        requestCode = START_DATE;
        break;
      case R.id.ib_project_end:
        dialog = new BaseYMDTimeDialogFragment();
        requestCode = END_DATE;
        break;

      default:
        break;
    }

    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog.setTargetFragment(RegistProjectProgressFragment.this, requestCode);
    dialog.show(fm, "");
  }

  private void volleyRegist() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PROJECT_REGIST);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("id", superContent.getId());
    params.put("actSTime", startDate);
    params.put("actETime", endDate);
    params.put("delayReason", mEtdelayCause.getText().toString());
    params.put("remark", mEtprojectRemark.getText().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        // 解析响应的字符串
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          Intent i = new Intent();
          i.putExtra(DetailProjectProgressFragment.EXTRA_TYPE, "regist");
          getActivity().setResult(Activity.RESULT_OK, i);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.wrong_data);
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == START_DATE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      startDate = MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
      mTvprojectStartTime.setText(startDate);
    }
    if (requestCode == END_DATE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      endDate = MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
      mTvprojectEndTime.setText(endDate);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public static RegistProjectProgressFragment newInstance(ProjectProgressSuper item,
      String projectName) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    args.putSerializable(EXTRA_PROJECT_NAME, projectName);
    RegistProjectProgressFragment fragment = new RegistProjectProgressFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
